<template>
    <div class="logisticsCompany_block">
        <div class="top">
            <search-bar v-model="searchModel" :search-data="searchData" :config="searchData" @search="handleSearchSubmit"
                @searchReset="handleSearchReset" style="margin-top:0;margin-left:-20px;padding-top:.2rem">
            </search-bar>
        </div>

        <div class="bottom">

            <div class="btn_area" size="medium">
                <el-button type="primary" size="medium" @click="add">新增</el-button>
                <el-dropdown @command="handleCommand" style="margin-left: 0.1rem">
                    <el-button size="medium">
                        批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="audit">审核</el-dropdown-item>
                        <el-dropdown-item command="import">启用</el-dropdown-item>
                        <el-dropdown-item command="export">禁用</el-dropdown-item>
                        <el-dropdown-item command="delete">删除</el-dropdown-item>

                    </el-dropdown-menu>
                </el-dropdown>
                <el-button type="" size="medium" style="margin-left: 0.1rem" @click="exportWay">导出</el-button>
            </div>
            <LPTablePage :show-index="false" :table-data="tableData" :table-column="tableColumn" :total="total"
                :current-page="currentPage" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"
                :selection="true" @handleSelectionChange="handleSelectionChange" ref="tablePage" :selectable="selectable">
                <template slot="auditStatus" slot-scope="scope">
                    <!-- <span v-if="scope.row.auditStatus == 0" class="green">
                        待审核
                    </span>
                    <span v-else-if="scope.row.auditStatus == 1" class="blue">
                        已通过
                    </span>
                    <span v-else class="orage">
                        已驳回
                    </span> -->
                    <div v-if="scope.row.auditStatus == 0" >
                        <ProcessDots :processStatus="'checkPending'"/>待审核
                    </div>
                    <div v-else-if="scope.row.auditStatus == 1" >
                        <ProcessDots :processStatus="'finished'"/>已通过
                    </div>
                    <div v-else >
                        <ProcessDots :processStatus="'rejected'"/>已驳回
                    </div>
                </template>
                <template slot="isEnabled" slot-scope="scope">

                    <el-switch v-model="scope.row.isEnabled" :active-value="1" :inactive-value="0"></el-switch>

                </template>
                <template slot="creationSource" slot-scope="scope">

                    <span v-if="scope.row.creationSource == 1">
                        外部
                    </span>
                    <span v-else>
                        内部
                    </span>
                </template>

            </LPTablePage>
        </div>
        <!-- 编辑or新增 -->
        <base-dialog :visible="addVisile" :title="(isEdit ? '编辑' : '新增') + '物流公司'" width="918px" class="addDictDialog"
            @handleDialogSubmit="handleAddSubmit" @handleDialogCancle="handleAddCancle">
            <el-form ref="dictForm" :model="dictModel" :rules="ruleRule" label-width="120px" class="dictForm"
                label-position="top" size="medium">
                <el-row :gutter="50">

                    <el-col :span="12">
                        <el-form-item label="物流公司名称:" prop="companyName">
                            <!-- <el-input v-model.trim="dictModel.companyName" placeholder="请输入">
                            </el-input> -->
                            <el-autocomplete style="width:100%" v-model="dictModel.companyName"
                                :fetch-suggestions="querySearchAsync" placeholder="请输入"
                                @select="handleSelect"></el-autocomplete>

                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物流公司编号:" prop="">
                            <el-input v-model.trim="dictModel.logisticsCompanyNumber" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="统一社会信用代码:" prop="unifiedSocialCreditCode">
                            <el-input v-model="dictModel.unifiedSocialCreditCode" placeholder="请输入" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="法人:" prop="legalPerson">
                            <el-input v-model="dictModel.legalPerson" placeholder="请输入" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所在区域:" prop="area">
                            <el-input v-model="dictModel.area" placeholder="请输入" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="详细地址:" prop="detailedAddress">
                            <el-input v-model="dictModel.detailedAddress" placeholder="请输入" disabled>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="关联用户帐号:">
                            <el-select style="width:100%" v-model="dictModel.associatedUserAccount"
                                :remote-method="getAccountQueryListWay" filterable default-first-option remote
                                placeholder="请选择">
                                <el-option v-for="(item) in accountQueryList" :key="item.id"
                                    :label="item.phone" :value="item.phone" :disabled="item.isbindDriver==1" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否启用:" prop="isEnabled">
                            <el-switch v-model="dictModel.isEnabled" />
                            <span class="ml20">关闭后物流公司在系统停止使用</span>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </base-dialog>
        <!-- 审核 -->
        <base-dialog :visible="auditVisile" title="审核" width="640px" class="addDictDialog"
            @handleDialogSubmit="handleAuditSubmit" @handleDialogCancle="handleAuditCancle">
            <el-form ref="auditParams" :model="auditParams" :rules="ruleRule" label-width="120px" class="dictForm"
                label-position="top" size="medium">
                <el-row :gutter="50">

                    <el-col :span="24">
                        <el-form-item label="审核结果:" prop="auditStatus">
                            <el-radio-group v-model="auditParams.auditStatus">
                                <el-radio :label="1">通过</el-radio>
                                <el-radio :label="2">驳回</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="审核说明:" prop="auditText">
                            <el-input v-model.trim="auditParams.auditText" type="textarea" :rows="2" placeholder="请输入">
                            </el-input>
                        </el-form-item>
                    </el-col>




                </el-row>


            </el-form>
        </base-dialog>
    </div>
</template>
    
<script>
import { validateNumber } from "@/utils/validate";
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
import ProcessDots from '@/components/ProcessDots'
import {
    logininforList,
    delLogininfor,
    cleanLogininfor
} from '@/api/system/logs'
import beiGangApi from '@/api/logistics/beigang';
import { addDateRange } from "@/utils/ruoyi";

// import {auditSuccess,auditReject} from "@/api/customer";


export default {
    name: "logisticsCompany",
    components: {
        LPTablePage, SearchBar, baseDialog,ProcessDots
    },
    data() {


        return {
            accountQueryList:[],
            auditParams: {
            },
            addVisile: false,
            auditVisile: false,
            auditList: [],
            isEdit: false,
            dictModel: {

                isEnabled: true
            },
            searchModel: {},
            timeout: null,// 定时器，用于控制请求频率
            searchData: [
                {
                    placeholder: "", prop: "auditStatus", type: 'radio',

                    options: [
                        { label: '待审核', value: '0',num:0 },
                        { label: '已通过', value: '1' ,num:0 },
                        { label: '已驳回', value: '2' ,num:0 },


                    ]
                },

                { placeholder: "物流公司编号", prop: "logisticsCompanyNumber", },
                { placeholder: "物流公司名称", prop: "companyName" },
                {
                    prop: 'isEnabled',
                    type: 'select',
                    placeholder: '是否启用',
                    options: [
                        { label: '禁用', value: '0' },
                        { label: '启用', value: '1' },

                    ]
                },
                {
                    prop: 'creationSource',
                    type: 'select',
                    placeholder: '创建来源',
                    options: [
                        { label: '内部', value: '0' },
                        { label: '外部', value: '1' },

                    ]
                },

                {
                    label: "创建时间", prop: "createTime", type: "daterangehms",
                    startPlaceholder: "起始时间",
                    endPlaceholder: "结束时间",
                    span: 6
                },
                {
                    prop: 'search',
                    type: 'button',
                    policy: ['system.log.query'],
                },
            ],
            tableData: [],
            tableColumn: [
                { label: "物流公司名称", prop: "companyName", },
                { label: "审核状态", prop: "auditStatus", render: true },
                { label: "关联用户账号", prop: "associatedUserAccount", },
                { label: "物流公司编号", prop: "logisticsCompanyNumber", },
                { label: "是否启用", prop: "isEnabled", render: true },
                { label: "统一社会信用代码", prop: "unifiedSocialCreditCode", },
                { label: "法人", prop: "legalPerson", },
                { label: "所在区域", prop: "area", },
                { label: "详细地址", prop: "detailedAddress", },
                { label: "操作时间", prop: "operationTime", },
                { label: "操作人", prop: "operator", },
                { label: "创建时间", prop: "creationTime", },
                { label: "创建人", prop: "creator", },
                { label: "创建来源", prop: "creationSource", render: true },
                {
                    label: '操作',
                    prop: 'action',
                    fixed: 'right',
                    type: 'button',
                    width: 170,
                    buttons: [
                        {
                            label: '查看',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            method: 'handleDetail',
                        },
                        {
                            label: '编辑',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            method: 'handleEdit',

                        },
                        {
                            label: '审核',
                            type: 'text',
                            color: 'rgba(0, 118, 255, 1)',
                            hide: 'auditStatus',
                            hideValue: [0],
                            method: 'handleAudit',

                        },
                        {
                            label: '删除',
                            type: 'text',
                            color: '#ee3333',
                            method: 'handleDelete',

                        },
                    ],
                },

                //  {
                //     label: "操作",
                //     prop: "action",
                //     type: "button",
                //     hideTooLtip:true,
                //     width:180,
                //     button:[
                //         {
                //             label: "查看",
                //             type: "text",
                //             icon: "el-icon-view",
                //             method:`_detail${this.$options.name}`
                //         },
                //         {
                //             label: "通过",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditSuccess${this.$options.name}`
                //         },
                //         {
                //             label: "驳回",
                //             type: "text",
                //             icon: "el-icon-view",
                //             hide:'isCanTakeAudit',
                //             // hide:'canTakeAudit',
                //             hideValue:[false],
                //             policy:['Crm.CluePoolManage.TakeAudit'],
                //             method:`_auditFail${this.$options.name}`
                //         },
                //     ]
                //  }   
            ],
            total: 0,
            currentPage: 1,
            selectArr: [],
            allotVisile: false,
            settingVisile: false,
            ruleModel: {},
            ruleRule: {
                companyName: [{ required: true, trigger: "blur", message: "必填" }],
                isEnabled: [{ required: true, trigger: "change", message: "必选" }],
                unifiedSocialCreditCode: [{ required: true, trigger: "blur", message: "必填" }],
                legalPerson: [{ required: true, trigger: "blur", message: "必填" }],
                area: [{ required: true, trigger: "blur", message: "必填" }],
                detailedAddress: [{ required: true, trigger: "blur", message: "必填" }],
                auditStatus: [{ required: true, trigger: "change", message: "必选" }],
            },
            detailVisible: false,
            detailId: '',
            openSeaClueId: '',
            status: null,
            isCanTakeAudit: null
        }
    },
    mounted() {
        this.getLogisticsCompanyStatus()
        this.getLogisticsCompanyList()
        // 详情
        this.$bus.$on('handleDetail', rows => {

            this.$router.push({ path: `/logistics/beiGang/logisticsCompanyDetail/${rows.id}` })
        })
        // 编辑
        this.$bus.$on('handleEdit', rows => {

            beiGangApi.getLogisticsCompanyDetail(rows.id).then(res => {
                if (res.code == 200) {
                    this.dictModel = {
                        ...res.data,
                        isEnabled: res.data.isEnabled == 1 ? true : false
                    }
                    this.addVisile = true
                    this.isEdit = true
                }
            })
            // this.dictModel = 
        })
        // 审核
        this.$bus.$on('handleAudit', rows => {
            let arr = []
            arr.push(rows)
            this.auditList = arr
            this.auditVisile = true

            // this.$router.push({ path: `/system/msg/edit/${rows.id}` })
        })

        // 删除
        this.$bus.$on('handleDelete', rows => {
            this.$confirm('确定删除吗', '取消', {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                //   console.log('确认');
                beiGangApi.delLogisticsCompany(rows.id).then(res => {
                    if (res.code == 200) {
                        this.$message.success("删除成功")
                        this.getLogisticsCompanyList()
                    }
                })
            })
        })
    },
    methods: {
        getLogisticsCompanyStatus(){
            beiGangApi.logisticsCompanyStatus(

            ).then(res=>{    
                let arr = Object.keys(res)
                arr.map(
                    item=>{
                        this.searchData[0].options.map(iem=>{
                            if(item==iem.value){
                                iem.num = res[item]
                            }
                        
                        })
                        
                    }
                )
                
                })
        },
        // 导出
        exportWay() {
            this.download('logistics/company/export', {
                ...this.searchData
            }, `物流公司_${new Date().getTime()}.xlsx`)
        },
        /*企业查询模糊搜索相关 start*/
        // beiGangApi.logisticsCompanyFuzzySearch(query)
        querySearchAsync(queryString, cb) {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(async () => {
                if (queryString) {
                    try {
                        // 调用接口获取数据
                        const results = await this.fetchRemoteData(queryString)
                        // const results1 = results .filter(item => item.includes(queryString))
                        // 将获取的数据传递给回调函数cb
                        cb(results);
                    } catch (error) {
                        console.error('Fetch error:', error);
                        cb([]); // 如果出错，传递一个空数组
                    }
                } else {
                    cb([]); // 如果queryString为空，传递一个空数组
                }
            }, 500); // 设置延时来减少请求频率
        },
        async fetchRemoteData(query) {
            const result = await beiGangApi.logisticsCompanyFuzzySearch({ companyName: query })
            // 模拟接口调用，实际应用中需要替换为真实的API调用
            const res1 = result.filter(item => item.companyName.includes(query));
            return res1.map((itm => {
                return {
                    ...itm,
                    value: itm.companyName
                }
            }))
        },
 // 关联用户帐号模拟查询操作
 getAccountQueryListWay(query){
             beiGangApi.getAccountQueryList({phone:query}).then(res=>{         
                if(res.code==200){
                    this.accountQueryList = res.data
                }
              
             })
        },
        handleSelect(item) {
            this.dictModel.unifiedSocialCreditCode = item.unifiedSocialCreditCode

            this.dictModel.legalPerson = item.legalPerson
            this.dictModel.area = item.area
            this, this.dictModel.detailedAddress = item.detailedAddress
        },

        /*企业查询模糊搜索相关 end*/

        // 批量操作
        handleCommand(command) {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选")
                return
            }
            const len = this.selectArr.length
            let title = '启用'
            let content = '确定要启用吗？'
            switch (command) {
                // 审核

                case 'audit':
                    this.auditWay()
                    break;
                // 启用
                case 'import':

                    if (len >= 2) {
                        title = '批量启用'
                        content = `已选择${len}项，确定要启用吗？`
                    }
                    this.setEnabled(
                        {
                            isEnabled: 1,
                            content,
                            title,
                        }
                    )
                    break;
                // 禁用
                case 'export':
                    title = '禁用'
                    content = '确定要禁用吗？'
                    if (len >= 2) {
                        title = '批量禁用'
                        content = `已选择${len}项，确定要禁用吗？`
                    }
                    this.setEnabled(
                        {
                            isEnabled: 0,
                            content,
                            title,
                        }
                    )
                    break;
                // 删除
                default:
                    this.setDel()
                    break;
            }
        },
        // 批量审核操作
        auditWay() {
            this.auditVisile = true
            this.auditList = this.selectArr
        },
        // 批量禁启用操作
        setEnabled(obj) {
            // let params = {
            //     ids: this.selectArr.map(item => item.id).join(','),
            //     isEnabled: obj.isEnabled
            // }
            let arr = this.selectArr.map(item => {
                return {
                    id: item.id,
                    isEnabled: obj.isEnabled
                }
            })

            this.$confirm(obj.content, obj.title, {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {

                beiGangApi.updateLogisticsCompanyList(arr).then(res => {
                    if (res.code == 200) {
                        this.$message.success("操作成功")
                        this.getLogisticsCompanyList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },

        //批量删除操作
        setDel() {
            if (this.selectArr.length == 0) {
                this.$message.warning("请先勾选")
                return
            }
            let content = '确定删除吗'
            let title = '删除'
            if (this.selectArr.length >= 2) {
                title = '批量删除'
                content = `已选择${this.selectArr.length}项，确定要删除吗？`
            }
            this.$confirm(content, title, {
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                closeOnClickModal: false
            }).then(() => {
                let ids = this.selectArr.map(item => item.id).join(',');

                beiGangApi.delLogisticsCompany(ids).then(res => {
                    if (res.code == 200) {
                        this.$message.success("操作成功")
                        this.getLogisticsCompanyList()
                        this.$refs.tablePage.clearSelection()
                    }
                })
            })
        },
        // 创建司机
        add() {
            this.isEdit = false;
            this.addVisile = true;
        },
        handleAddSubmit() {
            this.$refs.dictForm.validate(valid => {
                if (valid) {
                    let obj = {
                        ...this.dictModel,
                        isEnabled: this.dictModel.isEnabled == true ? 1 : 0
                    }
                    if (!this.isEdit) {
                        beiGangApi.addLogisticsCompany(obj).then(res => {
                            if (res.code == 200) {

                                this.dictModel = this.$options.data().dictModel
                                this.$message.success("添加成功")
                                this.addVisile = false;
                                this.getLogisticsCompanyList()
                            }
                        })
                    } else {
                        beiGangApi.updateLogisticsCompany(obj).then(res => {
                            if (res.code == 200) {
                                console.log('editDict', res);
                                this.dictModel = this.$options.data().dictModel
                                this.$message.success("编辑成功")
                                this.addVisile = false;
                                this.getLogisticsCompanyList()

                            }
                        })
                    }
                } else {
                    this.$message.warning("请检查字典信息")
                    return false
                }
            })
        },
        handleAddCancle() {

            this.dictModel = this.$options.data().dictModel
            this.resetForm("dictForm")
            this.addVisile = false;
        },
        // 审核操作
        handleAuditSubmit() {
            this.$refs.auditParams.validate(valid => {
                if (valid) {
                    let arr = this.auditList.map(item => {
                        return {
                            id: item.id,
                            ...this.auditParams
                        }
                    })
                    beiGangApi.updateLogisticsCompanyList(arr).then(res => {
                        if (res.code == 200) {
                            this.$message.success('审核成功')
                            this.auditVisile = false
                            this.auditList = []
                            this.auditParams = this.$options.data().auditParams
                            this.getLogisticsCompanyList()

                        }
                    })
                }
            })
        },
        handleAuditCancle() {
            this.auditParams = this.$options.data().auditParams
            this.resetForm("auditParams")
            this.auditVisile = false;
        },


        getLogisticsCompanyList() {
            // addDateRange

            let { pageSize } = this.$refs.tablePage;
            let params = {

                ...this.searchModel,
                pageSize: pageSize,
                pageNum: this.currentPage
            }
            let obj = addDateRange(params, this.searchModel.loginTime)
            delete obj.loginTime
            // logininforList
            beiGangApi.logisticsCompanyList(obj).then(res => {
                if (res.code==200) {

                    this.total = res.total;
                    this.tableData = res.rows
                
                }
            })
        },
        selectable(row, index) {
            return true
        },

        handleSearchSubmit() {
            this.currentPage = 1;
            this.getLogisticsCompanyList()
        },
        handleSearchReset() {
            this.currentPage = 1;
            this.$refs.tablePage.clearSelection()
            this.getLogisticsCompanyList()
        },
        handleSizeChange(v) {
            this.pageSize = v;
            this.currentPage = 1;
            this.getLogisticsCompanyList()
        },
        handleCurrentChange(v) {
            this.currentPage = v;
            this.getLogisticsCompanyList()
        },
        handleSelectionChange(v) {
            console.log('handleSelectionChange', v);
            this.selectArr = v
        },
        allot() {
            this.$modal.confirm('是否确认清空所有登录日志数据项？').then(function () {
                return cleanLogininfor();
            }).then(() => {
                this.getLogisticsCompanyList();
                this.$modal.msgSuccess("清空成功");
            }).catch(() => { });
        },




        gethtml(value) {
            if (value == null) {
                return;
            }
            var list = value.split(',');
            var resultStr = ""
            list.forEach(item => {
                if (item.includes("高") || item.includes("重要")) {
                    resultStr = resultStr + "<span style='color:#EE3333'>" + item + "</span>,";
                }
                else {
                    resultStr = resultStr + item + ",";
                }
            })
            if (resultStr != "") {
                return resultStr.slice(0, -1);
            }
        },
        showSettign() {
            getOpenSeaSetting().then(res => {
                if (!res.error) {
                    console.log('getOpenSeaSetting', res);
                    this.ruleModel = res;
                    this.settingVisile = true;
                }
            })
        },
        handleSettingSubmit() {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    console.log('ruleModel', this.ruleModel);
                    putOpenSeaStting(this.ruleModel).then(res => {
                        if (!res.error) {
                            this.$message.success("保存设置成功")
                            this.settingVisile = false;
                        }
                    })
                } else {
                    return false
                }
            })
        },
        handleSettingCancle() {
            this.settingVisile = false;
        },
        detailClose() {
            this.detailVisible = false;
            this.getLogisticsCompanyList()
        },
        handleAllot() {
            this.allotVisile = true;
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
    },
    destroyed() {
        this.$bus.$off('handleDetail')
        this.$bus.$off('handleDelete')
        this.$bus.$off('handleEdit')
        this.$bus.$off('handleAudit')


    },
}
</script>
    
<style lang="scss" scoped>
.logisticsCompany_block {

    // padding: 0 .2rem .2rem;
    .top {
        background-color: #fff;
        padding: 0 .3rem;
    }

    .bottom {
        .btn_area {
            margin-bottom: 0.2rem;
            margin-left: 0.3rem;
        }

        background-color: #fff;
        margin-top: 0.2rem;
        padding: 0.2rem 0rem;


    }




    .green {
        color: #2CAD00;
    }

    .orage {
        color: #EE7533;
    }

    .blue {
        color: #0076FF;
    }

    .red {
        color: #ff3333;
    }
}
</style>